package com.example.myjavafx.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 */
public class AudioController {
    @FXML private Button playButton;
    @FXML private Button pauseButton;
    @FXML private Button stopButton;
    @FXML private Slider volumeSlider;
    @FXML private Slider progressSlider;
    @FXML private Label timeLabel;
    @FXML private TableView<AudioFile> audioTableView;
    @FXML private TableColumn<AudioFile, String> fileNameColumn;
    @FXML private TableColumn<AudioFile, String> durationColumn;
    @FXML private TableColumn<AudioFile, String> statusColumn;

    private MediaPlayer mediaPlayer;
    private final ObservableList<AudioFile> audioFiles = FXCollections.observableArrayList();
    private AudioFile currentAudio;

    @FXML
    private void initialize() {
        // 初始化表格
        audioTableView.setItems(audioFiles);

        // 设置双击播放
        audioTableView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                AudioFile selectedFile = audioTableView.getSelectionModel().getSelectedItem();
                if (selectedFile != null) {
                    playAudioFile(selectedFile);
                }
            }
        });

        // 设置音量控制
        volumeSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (mediaPlayer != null) {
                mediaPlayer.setVolume(newValue.doubleValue() / 100.0);
            }
        });

        // 设置进度条控制
        progressSlider.setOnMouseReleased(event -> {
            if (mediaPlayer != null) {
                mediaPlayer.seek(Duration.seconds(progressSlider.getValue()));
            }
        });

        // 初始化按钮状态
        updateButtonStates(false);
    }

    @FXML
    private void handleAddAudio() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Audio Files", "*.mp3", "*.wav", "*.m4a")
        );
        File selectedFile = fileChooser.showOpenDialog(null);

        if (selectedFile != null) {
            AudioFile audioFile = new AudioFile(selectedFile);
            audioFiles.add(audioFile);
        }
    }

    @FXML
    private void handleDeleteAudio() {
        AudioFile selectedFile = audioTableView.getSelectionModel().getSelectedItem();
        if (selectedFile != null) {
            if (selectedFile == currentAudio && mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.dispose();
                mediaPlayer = null;
                currentAudio = null;
            }
            audioFiles.remove(selectedFile);
        }
    }

    @FXML
    private void handlePlay() {
        if (mediaPlayer != null) {
            mediaPlayer.play();
            updateButtonStates(true);
            currentAudio.setStatus("播放中");
        } else {
            AudioFile selectedFile = audioTableView.getSelectionModel().getSelectedItem();
            if (selectedFile != null) {
                playAudioFile(selectedFile);
            }
        }
    }

    @FXML
    private void handlePause() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            currentAudio.setStatus("已暂停");
        }
    }

    @FXML
    private void handleStop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            currentAudio.setStatus("已停止");
            updateButtonStates(false);
        }
    }

    private void playAudioFile(AudioFile audioFile) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.dispose();
        }

        try {
            Media media = new Media(audioFile.getFile().toURI().toString());
            mediaPlayer = new MediaPlayer(media);
            currentAudio = audioFile;

            mediaPlayer.setOnReady(() -> {
                Duration total = media.getDuration();
                progressSlider.setMax(total.toSeconds());
                updateTimeLabel(Duration.ZERO, total);
            });

            mediaPlayer.currentTimeProperty().addListener((observable, oldValue, newValue) -> {
                progressSlider.setValue(newValue.toSeconds());
                updateTimeLabel(newValue, mediaPlayer.getTotalDuration());
            });

            mediaPlayer.setVolume(volumeSlider.getValue() / 100.0);
            mediaPlayer.play();

            updateButtonStates(true);
            audioFile.setStatus("播放中");

            // 设置播放完成事件
            mediaPlayer.setOnEndOfMedia(() -> {
                mediaPlayer.stop();
                audioFile.setStatus("已完成");
                updateButtonStates(false);
            });

        } catch (Exception e) {
            showError("播放错误", "无法播放选中的音频文件: " + e.getMessage());
        }
    }

    private void updateTimeLabel(Duration current, Duration total) {
        String currentTime = formatDuration(current);
        String totalTime = formatDuration(total);
        timeLabel.setText(currentTime + " / " + totalTime);
    }

    private void updateButtonStates(boolean isPlaying) {
        playButton.setDisable(isPlaying);
        pauseButton.setDisable(!isPlaying);
        stopButton.setDisable(!isPlaying);
    }

    private String formatDuration(Duration duration) {
        long seconds = (long) duration.toSeconds();
        return String.format("%02d:%02d",
                TimeUnit.SECONDS.toMinutes(seconds),
                seconds % 60
        );
    }

    private void showError(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }


    /**
     * 音频文件模型类，用于存储音频文件的元数据。
     */
    public static class AudioFile {
        private final File file;
        private final SimpleStringProperty fileName;
        private final SimpleStringProperty duration;
        private final SimpleStringProperty status;

        public AudioFile(File file) {
            this.file = file;
            this.fileName = new SimpleStringProperty(file.getName());
            this.duration = new SimpleStringProperty("未知");
            this.status = new SimpleStringProperty("未播放");
        }

        public File getFile() {
            return file;
        }

        public String getFileName() {
            return fileName.get();
        }

        public String getDuration() {
            return duration.get();
        }

        public String getStatus() {
            return status.get();
        }

        public void setStatus(String status) {
            this.status.set(status);
        }
    }
}
